package com.example._9_springmvc.xzy.dao.impl;

import com.example._9_springmvc.xzy.dao.LoginLogDao;
import com.example._9_springmvc.xzy.pojo.LoginLog;

import java.sql.*;
import java.util.ArrayList;

public class LoginLogDaoImpl implements LoginLogDao {

    public void SaveLog(LoginLog loginLog) throws ClassNotFoundException, SQLException {
        //1.注册数据库的驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取数据库连接（里面内容依次是："jdbc:mysql://主机名:端口号/数据库名","用户名","登录密码"）
        Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/my?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root", "root");
        //3.需要执行的sql语句（?是占位符，代表一个参数）
        String sql = "INSERT INTO login_info (username, loginIP, loginTime) VALUES (?, ?, ?)";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1, loginLog.getUserName());
        pstmt.setString(2, loginLog.getLoginIP());
        pstmt.setString(3, loginLog.getLoginTime());
        pstmt.executeUpdate();
    }

    public ArrayList<LoginLog> getAllLoginInfo() throws ClassNotFoundException, SQLException {
        ArrayList<LoginLog> loginLogs = new ArrayList<LoginLog>();
        //1.注册数据库的驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取数据库连接（里面内容依次是："jdbc:mysql://主机名:端口号/数据库名","用户名","登录密码"）
        Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/my?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root", "root");
        String sql = "SELECT * FROM login_info";
        Statement stmt = null;
        ResultSet rs = null;
        stmt = connection.createStatement();
        rs = stmt.executeQuery(sql);
        while (rs.next()){
            LoginLog loginLog = new LoginLog();
            loginLog.setLoginID(rs.getInt("logid"));
            loginLog.setUserName(rs.getString("username"));
            loginLog.setLoginIP(rs.getString("loginIP"));
            loginLog.setLoginTime(rs.getString("loginTime"));
            loginLogs.add(loginLog);
        }
        return loginLogs;
    }
}
